/*
 * Lab3.cpp
 *
 *  Created on: 30.10.2013
 *      Author: ulgish
 */

#include <lab3/Lab3.h>
#include <unistd.h>
using DT::Room;
using DT::RoomSafely;
using DT::RoomPrinter;
using DT::Thinker;

Lab3::Lab3(int countOfThinkers, int maxCountOfThinkers, int minDuration)
{
	this->maxCountOfThinker = maxCountOfThinkers;
	this->countOfThinkers = countOfThinkers;
	room = new Room(this->maxCountOfThinker);
	roomSafely = new RoomSafely(this->maxCountOfThinker);
	thinkers = new Thinker*[countOfThinkers];
	for (int i = 0; i < countOfThinkers; i++){
		thinkers[i] = new Thinker(minDuration);
	}
}

void Lab3::goSafely(int timeOfModeling)
{
	RoomPrinter::delayInMs = 250;
	Thinker::isRoomSafely = true;
	roomSafely->open();
	printer.start(roomSafely);
	for (int i = 0; i < countOfThinkers; i++){
		thinkers[i]->start(roomSafely);
	}
	sleep(timeOfModeling);
	roomSafely->close();
	for (int i = 0; i < countOfThinkers; i++){
		thinkers[i]->wait(NULL);
	}
	printer.wait(NULL);
	DT::writer.flush();

}

void Lab3::goDanger(int timeOfModeling)
{
	RoomPrinter::delayInMs = 250;
	Thinker::isRoomSafely = false;
	printer.start(room);
	room->open();
	for (int i = 0; i < countOfThinkers; i++){
		thinkers[i]->start(room);
	}
	sleep(timeOfModeling);
	room->close();
	for (int i = 0; i < countOfThinkers; i++){
		thinkers[i]->wait(NULL);
	}
	printer.wait(NULL);
	DT::writer.flush();


}

Lab3::~Lab3() {
	// TODO Auto-generated destructor stub
	delete this->room;
	delete this->roomSafely;
	for (int i = 0; i < countOfThinkers; i++){
		delete this->thinkers[i];
	}
	delete []this->thinkers;
}
